const mongoose = require('mongoose');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs');

// 定义轮播图模型
const carouselSchema = new mongoose.Schema({
  _id: { type: String, required: true, unique: true },
  imageUrl: String,
  link: String,
  order: Number,
  buttonList: [{
    link: String
  }],
  fileId: { type: String, required: true, unique: true },
  fileHash: { type: String, required: true },
  filePath: { type: String, required: true }
});

// 生成文件哈希的静态方法
carouselSchema.statics.generateFileHash = async function(filePath) {
  return new Promise((resolve, reject) => {
    const hash = crypto.createHash('sha256');
    const stream = fs.createReadStream(filePath);
    
    stream.on('data', data => hash.update(data));
    stream.on('end', () => resolve(hash.digest('hex')));
    stream.on('error', reject);
  });
};

// 生成唯一文件ID的静态方法
carouselSchema.statics.generateFileId = function() {
  return crypto.randomBytes(16).toString('hex');
};
module.exports = mongoose.model('Carousel', carouselSchema);